Java syntax
part 11/36 Β· 136.0 KB total
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
case 'A':
doSomething(); // Triggered if ch == 'A'
break;
case 'B':
case 'C':
doSomethingElse(); // Triggered if ch == 'B' or ch == 'C'
break;
default:
doSomethingDifferent(); // Triggered in any other case
break;
}
switch expressions
Since Java 14 it has become possible to use switch expressions, which
use the new arrow syntax:
var result = switch (ch) {
case 'A' -> Result.GREAT;
case 'B', 'C' -> Result.FINE;
default -> throw new ThisIsNoGoodException();
};
Alternatively, there is a possibility to express the same with the yield
statement, although it is recommended to prefer the arrow syntax because
it avoids the problem of accidental fall throughs.
var result = switch (ch) {
case 'A':
yield Result.GREAT;
case 'B':
case 'C':
yield Result.FINE;
default:
throw new ThisIsNoGoodException();
};
Iteration statements
Iteration statements are statements that are repeatedly executed when a
given condition is evaluated as true. Since J2SE 5.0, Java has four
forms of such statements. The condition must have type boolean or
Boolean, meaning C's
while (1) {
doSomething();
}
results in a compilation error.
while loop
In the while loop, the test is done before each iteration.
while (i < 10) {
doSomething();
}
do ... while loop
In the do ... while loop, the test is done after each iteration.
Consequently, the code is always executed at least once.
// doSomething() is called at least once
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ